package query

import (
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"strings"
)

type OrderSort struct {
	Filed string // 排序字段
	Sort  bool   // true->desc, false->asc
}

// OrderDest 封装排序   如
func OrderDest(orderSorts []string) func(db *gorm.DB) *gorm.DB {
	orders := OrderParse(orderSorts)
	return func(db *gorm.DB) *gorm.DB {
		for _, v := range orders {
			db = db.Order(clause.OrderByColumn{Column: clause.Column{Name: v.Filed}, Desc: v.Sort})
		}
		return db
	}
}

// OrderParse 解析排序字段
func OrderParse(orderSorts []string) []OrderSort {
	orders := make([]OrderSort, 1, 3)
	for _, v := range orderSorts {
		split := strings.Split(v, "_")
		if len(split) == 2 {
			bl := false
			sort := split[1]
			if sort == "desc" {
				bl = true
			}
			orders = append(orders, OrderSort{Filed: split[0], Sort: bl})
		}
	}
	return orders
}
